<template>
	<div class="area-charts-container">
		<div v-if="areas.length === 0" class="empty-data">
			<el-empty description="暂无区域数据" />
		</div>
		<div v-else class="area-charts">
			<div
				v-for="area in areasWithData"
				:key="area.value || `area-${area.label}`"
				class="area-chart"
				ref="areaChartRefs"
			>
				<div class="area-header">
					<h4 class="area-title">{{ area.label }}</h4>
					<div class="area-stats">
						<span class="stat-item">开工率: {{ getAreaStartRateToToday(area) }}%</span>
						<span class="stat-item">完工率: {{ getAreaEndRateToToday(area) }}%</span>
						<span class="stat-item">时间进度率: {{ getAreaTimeProgressRate(area) }}%</span>
					</div>
				</div>
				<!-- 显示模式选择 -->
				<div class="display-mode-selector">
					<el-radio-group v-model="displayMode" size="small">
						<el-radio-button value="combined">合并显示</el-radio-button>
						<el-radio-button value="split">分离显示</el-radio-button>
					</el-radio-group>
				</div>
				<!-- 图表容器 -->
				<div class="combined-chart-container">
					<CombinedAreaChart 
						:chart-data="area.chartData" 
						:area-name="area.label"
						:show-time-progress="true"
						:show-split-layout="displayMode === 'split'"
						ref="combinedChartComponents"
					/>
				</div>
			</div>
		</div>
		
		<!-- 显示筛选信息 -->
		<div v-if="areas.length > 0 && areasWithData.length === 0" class="filter-info">
			<el-alert
				title="筛选结果"
				type="info"
				:closable="false"
				show-icon
			>
				<template #default>
					<div>当前筛选条件下，所选区域暂无数据</div>
					<div class="filter-details">
						<span v-if="queryParams.className">分类: {{ getClassNameLabel(queryParams.className) }}</span>
						<span v-if="queryParams.workTime">月份: {{ queryParams.workTime }}</span>
					</div>
				</template>
			</el-alert>
		</div>
	</div>
</template>

<script lang="ts" setup>
import { ref, reactive, watch, computed, nextTick, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { usePlanViewApi } from '/@/api/plans/planView';
import CombinedAreaChart from './CombinedAreaChart.vue';

interface Area {
	value: number | null;
	label: string;
	chartData: any[];
}

interface Props {
	areas: Array<{ value: number | null; label: string }>;
	queryParams: any;
	chartDataCache?: Record<number, any[]>; // 新增：图表数据缓存
}

const props = defineProps<Props>();
const planViewApi = usePlanViewApi();

const areas = ref<Area[]>([]);
const areaChartRefs = ref<HTMLElement[]>([]);
const combinedChartComponents = ref<any[]>([]);
const displayMode = ref<'combined' | 'split'>('combined');

// 只显示有数据的区域
const areasWithData = computed(() => {
	return areas.value.filter(area => 
		area.chartData && 
		area.chartData.length > 0 && 
		area.chartData.some(item => 
			item.planStart > 0 || 
			item.planEnd > 0 || 
			item.actualStart > 0 || 
			item.actualEnd > 0
		)
	);
});

// 获取分类名称
const getClassNameLabel = (classNameId: number | null) => {
	if (!classNameId) return '';
	// 这里可以从props中获取分类数据，或者通过API获取
	return `分类${classNameId}`;
};

// 为每个区域加载图表数据 - 完全依赖Store缓存
const loadAreaChartData = async () => {
	const promises = props.areas.map(async (area) => {
		try {
			// 完全依赖缓存数据，不再有API fallback
			const chartData = props.chartDataCache && area.value ? 
				(props.chartDataCache[area.value] || []) : [];
			
			return {
				...area,
				chartData: chartData
			};
		} catch (error) {
			console.error(`加载区域 ${area.label} 数据失败:`, error);
			return {
				...area,
				chartData: []
			};
		}
	});

	try {
		const results = await Promise.all(promises);
		areas.value = results;
		
		// 数据加载完成后，等待DOM更新并执行resize
		await nextTick();
		setTimeout(() => {
			resize();
		}, 100);
	} catch (error) {
		ElMessage.error('加载区域图表数据失败');
	}
};

// 计算区域到今天的开工率（保留一位小数）
const getAreaStartRateToToday = (area: Area) => {
	if (!area.chartData || area.chartData.length === 0) return 0;

	const today = new Date();
	const todayStr = today.toISOString().slice(0, 10);

	// 找到今天或最近的数据（找到最后一个满足条件的）
	const validData = area.chartData.filter(item => item.date <= todayStr);
	if (validData.length === 0) return 0;
	const todayData = validData[validData.length - 1];

	// 计算整个月的计划开工总数（最后一天的累计数就是总计划数）
	const lastDayData = area.chartData[area.chartData.length - 1];
	const planStartTotal = lastDayData.planStart || 0;
	if (planStartTotal === 0) return 0;

	// 保留一位小数
	const rate = (todayData.actualStart / planStartTotal) * 100;
	return Math.round(rate * 10) / 10;
};

// 计算区域到今天的完工率（保留一位小数）
const getAreaEndRateToToday = (area: Area) => {
	if (!area.chartData || area.chartData.length === 0) return 0;

	const today = new Date();
	const todayStr = today.toISOString().slice(0, 10);

	// 找到今天或最近的数据（找到最后一个满足条件的）
	const validData = area.chartData.filter(item => item.date <= todayStr);
	if (validData.length === 0) return 0;
	const todayData = validData[validData.length - 1];

	// 计算整个月的计划完工总数（最后一天的累计数就是总计划数）
	const lastDayData = area.chartData[area.chartData.length - 1];
	const planEndTotal = lastDayData.planEnd || 0;
	if (planEndTotal === 0) return 0;

	// 保留一位小数
	const rate = (todayData.actualEnd / planEndTotal) * 100;
	return Math.round(rate * 10) / 10;
};

// 计算时间进度率（因领导要求需要推迟1天，但到最后一天显示100%）
const getAreaTimeProgressRate = (area: Area) => {
	if (!area.chartData || area.chartData.length === 0) return 0;

	const today = new Date();
	const todayStr = today.toISOString().slice(0, 10);

	// 计算已经过去的天数
	const totalDays = area.chartData.length;
	const passedDaysRaw = area.chartData.filter(item => item.date <= todayStr).length;

	// 如果已经到达或超过最后一天，显示100%
	if (passedDaysRaw >= totalDays) {
		return 100;
	}

	// 否则，推迟1天显示（保留至少1天的最小值）
	const passedDays = Math.max(1, passedDaysRaw - 1);
	const rate = (passedDays / totalDays) * 100;
	return Math.round(rate * 10) / 10;
};

// 暴露resize方法给父组件
const resize = () => {
	nextTick(() => {
		// 调用合并图表组件的resize方法
		if (combinedChartComponents.value && Array.isArray(combinedChartComponents.value)) {
			combinedChartComponents.value.forEach((chartComponent, index) => {
				if (chartComponent && typeof chartComponent.resize === 'function') {
					setTimeout(() => {
						chartComponent.resize();
					}, index * 50); // 错开时间，避免同时resize
				}
			});
		}
	});
};

// 监听查询参数变化
watch(() => props.queryParams, () => {
	loadAreaChartData();
}, { deep: true });

// 监听区域列表变化
watch(() => props.areas, () => {
	loadAreaChartData();
}, { deep: true });

// 监听缓存数据变化
watch(() => props.chartDataCache, () => {
	loadAreaChartData();
}, { deep: true });

// 暴露方法给父组件
defineExpose({
	resize
});

// 初始化加载
onMounted(() => {
	loadAreaChartData();
});
</script>

<style lang="scss" scoped>
.area-charts-container {
	width: 100%;
	
	.empty-data {
		padding: 40px;
		text-align: center;
	}
	
	.filter-info {
		margin-top: 20px;
		
		.filter-details {
			margin-top: 8px;
			font-size: 12px;
			color: var(--el-text-color-secondary);
			
			span {
				margin-right: 15px;
				
				&:last-child {
					margin-right: 0;
				}
			}
		}
	}
	
	.area-charts {
		.area-chart {
			margin-bottom: 30px;
			padding: 20px;
			border: 1px solid var(--el-border-color-light);
			border-radius: 4px;
			background: var(--el-bg-color);
			box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
			
			.area-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 15px;
				
				.area-title {
					margin: 0;
					font-size: 16px;
					font-weight: 600;
					color: var(--el-text-color-primary);
				}
				
				.area-stats {
					.stat-item {
						margin-left: 15px;
						font-size: 12px;
						color: var(--el-text-color-secondary);
						
						&:first-child {
							margin-left: 0;
						}
					}
				}
			}
			
			.display-mode-selector {
				text-align: center;
				margin-bottom: 15px;
				padding-bottom: 10px;
				border-bottom: 1px solid var(--el-border-color-lighter);
			}
			
			.combined-chart-container {
				height: 400px;
				background: var(--el-bg-color);
				border-radius: 4px;
				padding: 15px;
				border: 1px solid var(--el-border-color-light);
				box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
			}
		}
	}
}
</style> 